(ns pe.p39)

(defn hypo-from-legs [a b] (Math/sqrt (+ (* a a) (* b b))))

(defn perim-from-legs [a b] (+ a b (hypo-from-legs a b)))

(defn integer-num? [n] (= n (int n)))

(defn perim-ok? [a b]
  (let [perim (perim-from-legs a b)]
    (and (< perim 1001) (integer-num? perim))))

(defn all-valid-perims []
  (for [a (range 1 1000) b (range a 1000) :when (perim-ok? a b)]
    {:a a, :b b, :c (int (hypo-from-legs a b)), :p (int (perim-from-legs a b))}))

(defn group-solutions [perims]
  (loop [perim (first perims) perims (next perims) grouped {}]
    (if perim
      (recur (first perims) (next perims) (merge-with concat {(:p perim) [perim]} grouped))
      grouped)))


(println
  (reduce
    (fn [[cnt1 p1 :as entry1] [cnt2 p2 :as entry2]] (if (> cnt1 cnt2) entry1 entry2))
    (map
      (fn [[p solutions]] [(count solutions) p])
      (group-solutions (all-valid-perims)))))